package com.kl.oss.tencent;

import com.qcloud.cos.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 上传腾讯云
 */
@RestController
@RequestMapping(value = "/tencent")
public class TencentOssUploadController {

    @Value("${tencent.cloud.oss.bucketName}")
    private String bucketName;

    @Autowired
    private TencentCosManager manager;

    @PostMapping(value = "/upload")
    public PutObjectResult uploadToTencentOss(@RequestBody Object jsonConfig, @RequestParam(required = false) String configName) {
        CosUploadReq uploadReq = new CosUploadReq();
        uploadReq.setBucketName(bucketName);
        if (configName == null) {
            configName = System.currentTimeMillis() + "";
        }
        System.out.println("文件名=" + configName);
        uploadReq.setStoreName(configName);
        uploadReq.setContent(objectToByteArray(jsonConfig));
        return manager.putObject(uploadReq);
    }

    @PostMapping(value = "/download")
    public Object downLoadFromTencentOss(@RequestParam("key") String objectKey) {
        return manager.downLoadFile(bucketName, objectKey);
    }

    /**
     * 对象转Byte数组
     */
    public static byte[] objectToByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            objectOutputStream.flush();
            bytes = byteArrayOutputStream.toByteArray();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return bytes;
    }
}
